package pers.qianyu.util;

import cn.hutool.core.collection.*;

import javax.validation.*;
import java.util.*;

/**
 * 校验工具类
 *
 * @author mizzle rain
 * @date 2020-10-13 17:26
 */
public class ValidatorUtils {
    /**
     * 校验器
     */
    private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 参数校验
     *
     * @param object 要校验的对象
     * @param groups 分组
     * @param <T>    校验对象的类型
     */
    public static <T> void validate(T object, Class<?>... groups) {
        Set<ConstraintViolation<T>> set = VALIDATOR.validate(object, groups);
        if (CollectionUtil.isNotEmpty(set)) {
            StringBuilder exceptionMessage = new StringBuilder();
            for (ConstraintViolation<T> violation : set) {
                exceptionMessage.append(violation.getMessage());
            }
            throw new RuntimeException(exceptionMessage.toString());
        }
    }
}
